import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // 作用：把X-Token（字段名） + 1111（值）添加到请求头
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 如果响应状态码是2xx，自动执行第一个函数，如果不是2xx（1xx、...）自动执行第二个函数
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res instanceof Blob) {
      return res
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 10000 && res.success === false) {
      Message({
        message: res.message || '网络异常！',
        type: 'error',
        duration: 5 * 1000 // 提示时长
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // 显示“对象”原本的样式
    const { response: { status }} = error
    if (status === 401) {
      // 如果状态码是401 ，证明token失效了
      // 1，开始删除cookie里面数据，初始化用户数据
      store.commit('user/RESET_STATE')
      // 2,跳转到登录页面
      router.replace('/login')
    }
    return Promise.reject(error)
  }
)

export default service
